package com.xiaoshuidi.cloud.module.rooms.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.module.rooms.api.roomhouse.RoomHouseApi;
import com.xiaoshuidi.cloud.module.rooms.api.roomhouse.vo.FreezeRepairReqVO;
import com.xiaoshuidi.cloud.module.rooms.api.roomhouse.vo.RoomHouseFilingsResp;
import com.xiaoshuidi.cloud.module.rooms.api.roomhouse.vo.RoomHouseMonthRentalDto;
import com.xiaoshuidi.cloud.module.rooms.api.roomhouse.vo.UpdateContractInfoByRenewalReqVO;
import com.xiaoshuidi.cloud.module.rooms.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.rooms.job.xxljob.RoomEsRebuildJob;
import com.xiaoshuidi.cloud.module.rooms.mapper.RoomHouseReserveMapper;
import com.xiaoshuidi.cloud.module.rooms.pojo.*;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomHouseFilingsRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomHouseInfoRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomHouseRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomHouseTypeRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.elsticsearch.RoomelEntityRepository;
import com.xiaoshuidi.cloud.module.rooms.service.RoomHouseService;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomHouseReserveVo;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomHouseRespVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

import static com.xiaoshuidi.cloud.module.system.enums.ApiConstants.VERSION;

/**
 * @author hans.zhang
 */
@Slf4j
@RestController
@DubboService(version = VERSION)
@Validated
@RequiredArgsConstructor
public class RoomHouseApiImpl implements RoomHouseApi {

    private final RoomHouseService roomHouseService;
    private final RoomHouseRepository roomHouseRepository;
    private final RoomHouseFilingsRepository filingsRepository;
    private final RoomHouseInfoRepository roomHouseInfoRepository;
    private final RoomHouseTypeRepository roomHouseTypeRepository;
    private final RoomelEntityRepository roomelEntityRepository;
    private final RoomEsRebuildJob roomEsRebuildJob;
    @Autowired
    private RoomHouseReserveMapper roomHouseReserveMapper;

    @Override
    public CommonResult<Boolean> repairFinish(Long roomHouseId) {
        return roomHouseService.repairFinish(roomHouseId);
    }

    @Override
    public CommonResult<List<RoomHouseRespVo>> getRoomHouseByIds(List<Long> ids) {
        return roomHouseService.getRoomHouseByIds(ids);
    }

    @Override
    public CommonResult<RoomHouseRespVo> getRoomHouseinfoById(Long roomHouseId) {
        return roomHouseService.getRoomHouseinfoById(roomHouseId);
    }

    @Override
    public CommonResult<RoomHouseRespVo> queryByAddr(String roomHouseAddr,Long apartmentId) {
        return roomHouseService.queryByHouseAddr(roomHouseAddr,apartmentId);
    }

    @Override
    public CommonResult<List<RoomHouseMonthRentalDto>> listMonthRental(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "参数不能为空");
        }
        List<RoomHouse> roomHouseList = roomHouseRepository.listByIds(ids);
        List<RoomHouseMonthRentalDto> dtos = roomHouseList.stream().map(s -> {
            RoomHouseMonthRentalDto dto = new RoomHouseMonthRentalDto();
            dto.setId(s.getId());
            dto.setMonthRental(s.getMonthRental() == null ? null : BigDecimal.valueOf(s.getMonthRental()).setScale(2, RoundingMode.HALF_UP));
            return dto;
        }).collect(Collectors.toList());
        return CommonResult.success(dtos);
    }

    @Override
    public CommonResult<Boolean> roomFreezeByDeptId(Long deptId) {
        log.info("根据部门冻结房源Api接口被调用，deptId:{}", deptId);
        return roomHouseService.roomFreezeByDeptId(deptId);
    }

    @Override
    public CommonResult<Boolean> roomUnFreezeByDeptId(Long deptId) {
        log.info("根据部门解冻房源Api接口被调用，deptId:{}", deptId);
        return roomHouseService.roomUnFreezeByDeptId(deptId);
    }

    @Override
    public CommonResult<Long> roomFreeze(FreezeRepairReqVO freezeRepairReqVO) {
        log.info("根据房源id冻结Api接口被调用，roomHouseId:{}", freezeRepairReqVO.getRoomHouseId());
        return roomHouseService.roomFreeze(freezeRepairReqVO.getRoomHouseId());
    }

    @Override
    public CommonResult<Long> roomUnFreeze(FreezeRepairReqVO freezeRepairReqVO) {
        log.info("根据房源id解冻Api接口被调用，roomHouseId:{}", freezeRepairReqVO.getRoomHouseId());
        return roomHouseService.roomUnFreeze(freezeRepairReqVO.getRoomHouseId());
    }

    @Override
    public CommonResult<RoomHouseFilingsResp> getFilingsByRoomId(Long roomHouseId) {
        RoomHouse house = roomHouseRepository.getById(roomHouseId);
        if (house == null) {
            log.error("房源信息不存在");
            return CommonResult.error(ErrorCodeConstants.HOUSE_NOT_EXISTS);
        }

        RoomHouseFilings filings = filingsRepository.getByRoomHouseId(roomHouseId);
        RoomHouseInfo houseInfo = roomHouseInfoRepository.getByRoomHouseId(house.getId());
        RoomHouseType roomHouseType = roomHouseTypeRepository.getById(house.getRoomHouseTypeId());
        if (ObjectUtil.isEmpty(roomHouseType)) {
            log.error("户型信息不存在");
            return CommonResult.error(ErrorCodeConstants.HOUSE_TYPE_NOT_EXISTS);
        }
        StringBuilder sb = new StringBuilder();
        sb.append(house.getDistrict());
        sb.append(house.getStreet());
        sb.append(house.getArea());
        sb.append(house.getBuildingNo());
        sb.append("栋");
        if(!house.getIsConcentrated()){
            sb.append(house.getUnitNo());
            sb.append("单元");
        }
        sb.append(house.getHouseNo());

        RoomHouseFilingsResp resp = RoomHouseFilingsResp.builder()
                .isWhole(house.getIsWhole())
                .space(house.getSpace())
                .roomHouseId(house.getId())
                .superRoomHouseId(house.getSuperId())
                .address(sb.toString())
                .bedRoomNum(roomHouseType.getBedRoomNum())
                .livingRoomNum(roomHouseType.getLivingRoomNum())
                .decoration(house.getDecoration())
                .peopleNum(house.getPeopleNum())
                .propertyType(houseInfo.getPropertyType())
                .propertyNo(houseInfo.getPropertyNo())
                .build();
        if (filings != null) {
            resp.setExternalHouseId(filings.getExternalHouseId());
            resp.setSuperExternalHouseId(filings.getSupperHouseId());
        }
        if (houseInfo != null) {
            resp.setOwnerName(houseInfo.getOwnerName());
            resp.setOwnerPhone(houseInfo.getTelPhone());
            resp.setOwnerCardType(houseInfo.getCardType());
            resp.setOwnerCardNo(houseInfo.getCardNo());
        }
        return CommonResult.success(resp);
    }

    /**
     * 续租合同账单支付后,更新房源的续租合同信息
     * @param reqVO
     * @return
     */
    @Override
    public CommonResult<Boolean> updateContractInfoByRenewal(UpdateContractInfoByRenewalReqVO reqVO) {
        log.info("续租合同账单支付后,更新房源的续租合同信息Api接口被调用:{}", JsonUtils.toJsonString(reqVO));
        return roomHouseService.updateContractInfoByRenewal(reqVO.getRoomHouseId(), reqVO.getRenewalContractId(), reqVO.getRenewalEndTime());
    }


    /**
     * 根据房间id列表更新es房源数据
     * @param ids
     * @return
     */
    @Override
    public CommonResult<Boolean> updateESRoomByIds(List<Long> ids) {
        log.info("根据房间id列表更新es房源数据,房源id：{}", JsonUtils.toJsonString(ids));
        for (Long id : ids) {
            roomEsRebuildJob.rebuildRoomsEsIndex(id);
        }
        return CommonResult.success(Boolean.TRUE);
    }

    @Override
    public CommonResult<List<RoomHouseRespVo>> getRoomHouseAndLayoutByIds(List<Long> ids) {
        return roomHouseService.getRoomHouseAndLayoutByIds(ids);
    }

    /**
     * 查询房源预约信息
     * @return
     */
    @Override
    public CommonResult<List<RoomHouseReserveVo>> getRoomHouseReserve(String checkInDate,Long apartmentId){
        LambdaQueryWrapper<RoomHouseReserve> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RoomHouseReserve::getDeleted, 0);
        wrapper.eq(RoomHouseReserve::getCheckInDate, checkInDate);
        wrapper.eq(RoomHouseReserve::getStatus, 2);//已签订
        wrapper.eq(RoomHouseReserve::getApartmentId, apartmentId);//已签订
        List<RoomHouseReserve> roomHouseReserves = roomHouseReserveMapper.selectList(wrapper);
        List<RoomHouseReserveVo> roomHouseReserveVos = BeanUtil.copyToList(roomHouseReserves, RoomHouseReserveVo.class);
        return CommonResult.success(roomHouseReserveVos);
    }
}
